package com.it.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Objects;

/**
 * 请求日志过滤器
 */
@Component
@Slf4j
public class LoggingFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethodValue();
        
        // 获取客户端IP
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String clientIp = Objects.nonNull(remoteAddress) ? remoteAddress.getHostString() : "unknown";
        
        // 记录请求信息
        log.info("收到请求 - IP: {}, Method: {}, Path: {}", clientIp, method, path);
        
        // 请求开始时间
        long startTime = System.currentTimeMillis();
        
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 计算请求耗时
            long duration = System.currentTimeMillis() - startTime;
            // 记录响应信息
            log.info("请求完成 - IP: {}, Method: {}, Path: {}, 耗时: {}ms, 状态码: {}", 
                    clientIp, method, path, duration, exchange.getResponse().getStatusCode());
        }));
    }

    @Override
    public int getOrder() {
        return -200; // 优先级高于认证过滤器，先记录请求信息
    }
} 